package com.blackrock.das.web.converters;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;

/**
 * The Class CustomMappingJackson2HttpMessageConverter.
 */
public class CustomMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

    /**
     * Instantiates a new custom mapping jackson2 http message converter.
     */
    public CustomMappingJackson2HttpMessageConverter() {
        this(true);
    }

    /**
     * Instantiates a new custom mapping jackson2 http message converter.
     * 
     * @param useBinary use binary format
     */
    public CustomMappingJackson2HttpMessageConverter(boolean useBinary) {

        if (useBinary) {
            setObjectMapper(new ObjectMapper(new SmileFactory()));
        }

        ObjectMapper objectMapper = getObjectMapper();

        // Don't fail for empty beans
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        // Don't serialize null values of map
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

        // Don't serialize null values
        objectMapper.setSerializationInclusion(Include.NON_NULL);

        // Serialize only fields not getters. Default behaviour is to serialize getters even if property doesn't exist
        objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
        objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

        // Enabling Default Typing, Polymorphism is done in PortfolioData class via JsonTypeInfo
        objectMapper.enableDefaultTyping(DefaultTyping.JAVA_LANG_OBJECT, As.PROPERTY);

        // Pretty printing the json output for more readability
        setPrettyPrint(false);
    }

}
